package ppa.marc.importer.data;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.collections.Predicate;

import ppa.marc.domain.Field;
import ppa.marc.domain.Record;

public class RecordIdentityExtractor {
	private static final int ID_SUBFIELD_LOCATION = 0;
	private static final int ID_FIELD_ID = 1;

	public String extractIdentityFrom(Record record) throws DataIntegrityException {
		if(record == null) throw new DataIntegrityException("Record is null.");
		Field idField = locateIdField(record);
		if(idField == null) throw new DataIntegrityException("Record doesn't have Unimarc identifier field.");
		if(idField.getSubFields().isEmpty()) throw new DataIntegrityException("Record's identifier field doesn't have subfield with a value.");
		return (idField.getSubFields().get(ID_SUBFIELD_LOCATION).getValue());
	}

	private Field locateIdField(Record record) {
		Field idField = (Field) CollectionUtils.find(record.getFields(), new Predicate() {
			@Override
			public boolean evaluate(Object fieldAsObject) {
				Field field = (Field) fieldAsObject;
				return (field.getId() == ID_FIELD_ID);
			}
		});
		return idField;
	}
}
